<template>
    <div class="common-layout">
        <el-container>
            <el-aside width="200px">
                <el-tree ref="treeRef" style="max-width: 600px" class="filter-tree" :data="data"
                    :props="defaultProps" default-expand-all :filter-node-method="filterNode"
                    @node-click="handleNodeClick" />
            </el-aside>
            <div class="vertical-divider"></div>
            <el-main>
                <el-form-item label="父级" prop="sortId">
                    <el-select v-model="ruleForm.sortId" placeholder="请选择父级" style="width: 310px">
                        <el-option v-for="item in parentinfo" :key="item.id" :label="item.templateName"
                            :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="上传" prop="templateName">
                    <el-input v-model="ruleForm.templateName" style="width: 200px;" />
                    <el-button type="primary" style="width: 100px;margin-left: 10px;" @click="uploadDialogVisible = true">上传文件</el-button>
                    <div v-if="uploadedFile.name" style="margin-left: 10px; color: #409EFF;">
                        已上传文件：{{ uploadedFile.name }}
                    </div>
                </el-form-item>
                <el-button type="primary" style="margin-left: 10px;" @click="addTemplate">添加</el-button>
                <el-button type="primary" style="margin-left: 10px;" @click="editTemplate"
                    v-if="ruleForm.fileUrl != ''">编辑</el-button>
                <el-button type="primary" style="margin-left: 10px;" v-if="ruleForm.fileUrl == ''"
                    disabled>编辑</el-button>
                <el-button type="primary" style="margin-left: 10px;" @click="delTemple"
                    v-if="ruleForm.fileUrl != ''">删除</el-button>
                <el-button type="primary" style="margin-left: 10px;" v-if="ruleForm.fileUrl == ''"
                    disabled>删除</el-button>
            </el-main>
        </el-container>
        <el-dialog v-model="uploadDialogVisible" title="上传文件" width="600px" :close-on-click-modal="false" draggable>
            <el-alert title="只能上传jpg / png / mp4 / pdf格式文件，文件大小100M以内" type="info" show-icon
                style="margin-bottom: 16px;" />
            <el-upload ref="uploadRef" action="http://localhost:9991/api/BroadController/UpdateFile"
                :file-list="uploadFileList" :auto-upload="true" :limit="20" :on-success="handleUploadSuccess"
                :on-change="handleFileChange" :on-remove="handleFileRemove" :before-upload="beforeUpload"
                accept=".jpg,.png,.mp4,.pdf" drag style="width:100%" multiple list-type="text">
                <el-button type="primary">继续选择</el-button>
                <div class="el-upload__tip">或将文件拖到这里，单次最多可传20个文件</div>
            </el-upload>
            <template #footer>
                <el-button @click="onUploadCancel">取消</el-button>
                <el-button type="primary" @click="onUploadConfirm">确定</el-button>
            </template>
        </el-dialog>
        <el-alert v-if="showErrorAlert" :title="errorAlertMsg" type="error" show-icon :closable="true"
            @close="showErrorAlert = false" style="margin: 16px 0;" />
    </div>
</template>

<style scoped>
.vertical-divider {
  width: 0;
  border-left: 2px dashed #ccc;
  height: auto;
  min-height: 100%;
  margin: 0 32px;
  box-sizing: border-box;
  align-self: stretch;
}
</style>

<script lang="ts" setup>
import { ref, watch, onMounted, reactive } from 'vue'
import { ElMessage, type TreeInstance, ElMessageBox } from 'element-plus'
import http from '@/api/http'

onMounted(() => {
    treeshow()
    parentIdList()
})




const ruleForm: any = reactive({
    id: '',
    templateName: '',
    broadCastTypeId: '',
    broadCastContent: '',
    fileUrl: '',
    sortId: '',
    isUse: '',
    createTime: ''

})

const delTemple = () => {
    ElMessageBox.confirm(
        '你是否确定删除此数据?',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            http.post('/api/BroadController/DeleteBroadCastTemplate', ruleForm.id).then((res: any) => {
                if (res.status) {
                    ElMessage.success("删除成功");
                    window.location.reload();
                }
                else {
                    errorAlertMsg.value = '当前文件夹下已有文件，请先删除文件/后再删除文件夹';
                    showErrorAlert.value = true;
                    return;
                }

            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })


}

const editTemplate = () => {
    if (!ruleForm.templateName) {
        ElMessage.warning('请填写名称');
        return;
    }
    if (uploadFileList.value.length === 0) {
        ElMessage.warning('请先上传文件');
        return;
    }
    // 拼接所有文件路径（url）
    ruleForm.fileUrl = uploadFileList.value.map((f: any) => f.url).join(',');
    http.post('/api/BroadController/UpdateBroadCastTemplate', ruleForm).then(res => {
        ElMessage.success('编辑成功')
        window.location.reload();
    })
}

const handleNodeClick = (node: any) => {
    console.log("点击树形", node)
    ruleForm.id = node.value
    ruleForm.sortId = node.sortId
    ruleForm.templateName = node.name
    ruleForm.fileUrl = node.url
    ruleForm.broadCastTypeId = node.broadCastTypeId
    ruleForm.broadCastContent = node.broadCastContent
    ruleForm.isUse = node.isUse
    ruleForm.createTime = node.createTime
    uploadedFile.value.name = node.url
    // 反填上传文件列表
    if (node.url) {
        const urls = node.url.split(',');
        uploadFileList.value = urls.filter(Boolean).map((url: string) => {
            // 提取文件名
            const name = url.split('/').pop() || url;
            return { name, url };
        });
    } else {
        uploadFileList.value = [];
    }
    console.log("ruleForm", ruleForm)
}


// 用于展示上传文件信息
const uploadedFile = ref<{ name: string }>({ name: '' });

// 上传成功回调
const handleUploadSuccess = (response: any, file: any) => {
    file.url = response.data?.url || response.url;
    uploadedFile.value.name = file.url;
    ElMessage.success('文件上传成功');
};

const addTemplate = () => {
    if (!ruleForm.templateName) {
        ElMessage.warning('请填写名称');
        return;
    }
    if (uploadFileList.value.length === 0) {
        ElMessage.warning('请先上传文件');
        return;
    }
    // 拼接所有文件路径（url）
    ruleForm.fileUrl = uploadFileList.value.map(f => f.url).join(',');
    // 递归获取所有节点
    function getAllNodes(tree: any[]): any[] {
        let result: any[] = [];
        tree.forEach(node => {
            result.push(node);
            if (node.children && node.children.length > 0) {
                result = result.concat(getAllNodes(node.children));
            }
        });
        return result;
    }
    const allNodes = getAllNodes(data.value);
    // 判断是否有重复
    const isDuplicate = allNodes.some((item: any) => item.url === ruleForm.fileUrl);

    if (isDuplicate) {
        ElMessageBox.confirm(
            '当前已有此文档，你是否确定重新上传并覆盖此数据？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(() => {
            // 用户点击确定，继续添加
            http.post('/api/BroadController/CreateBroadCastTemplate', ruleForm).then(res => {
                ElMessage.success('添加成功')
                window.location.reload();
            })
        }).catch(() => {
            // 用户点击取消，不做任何操作
            ElMessage.info('已取消添加');
        });
        return;
    }
    // 没有重复，直接添加
    http.post('/api/BroadController/CreateBroadCastTemplate', ruleForm).then(res => {
        ElMessage.success('添加成功')
        window.location.reload();
    })
}

interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'name',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.label.includes(value)
}

const parentinfo: any = ref([])
const parentIdList = () => {
    http.get('/api/BroadController/GetBroadCastTemplateDad').then(res => {
        parentinfo.value = res.data
    })
}

const treeshow = () => {
    http.get('/api/BroadController/ShowBroadCastTemplateList').then(res => {
        data.value = res.data
        console.log("树形列表数据:", data.value) // 添加这行来打印数据
    })
}

const data = ref([])

// 递归获取所有节点
function getAllNodes(tree: any[]): any[] {
    let result: any[] = [];
    tree.forEach(node => {
        result.push(node);
        if (node.children && node.children.length > 0) {
            result = result.concat(getAllNodes(node.children));
        }
    });
    return result;
}

const uploadDialogVisible = ref(false);
const uploadFileList = ref<any[]>([]);
const uploadRef = ref();

const handleFileChange = (file: any, fileList: any[]) => {
    uploadFileList.value = fileList;
};
const handleFileRemove = (file: any, fileList: any[]) => {
    uploadFileList.value = fileList;
};
const beforeUpload = (file: any) => {
    const isAllowedType = ['image/jpeg', 'image/png', 'video/mp4', 'application/pdf'].includes(file.type);
    const isLt100M = file.size / 1024 / 1024 < 100;
    if (!isAllowedType) {
        ElMessage.error('只能上传jpg/png/mp4/pdf格式文件');
        return false;
    }
    if (!isLt100M) {
        ElMessage.error('文件大小不能超过100MB');
        return false;
    }
    return true;
};

const onUploadConfirm = () => {
    uploadDialogVisible.value = false;
    // 不清除uploadFileList
};
const onUploadCancel = () => {
    uploadDialogVisible.value = false;
    uploadFileList.value = [];
    uploadedFile.value.name = '';
};

const showErrorAlert = ref(false);
const errorAlertMsg = ref('');

</script>
